import { ref, unref, computed, watch } from 'vue';

function useHover(el, props = {}) {
	
	const isHover = ref(false);
	
	watch(el, (newEl, oldEl, onInvalidate) => {
		if (newEl instanceof Element) {
			isHover.value = false;
			newEl.addEventListener('mouseenter', enter);
			newEl.addEventListener('mouseleave', leave);
			newEl.addEventListener('touchstart', enter);
			newEl.addEventListener('touchend', leave);
			onInvalidate(() => {
				newEl.removeEventListener('mouseenter', enter);
				newEl.removeEventListener('mouseleave', leave);
				newEl.removeEventListener('touchstart', enter);
				newEl.removeEventListener('touchend', leave);
			})
		}
	}, {
		immediate: true
	})
	
	function enter(e) {
		isHover.value = true;
		props.onEnter?.(e);
	}
	
	function leave(e) {
		isHover.value = false;
		props.onLeave?.(e);
	}
	
	return {
		isHover
	}
	
}

export default useHover;